package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class StaticResourceUtil {

    /**
     * 功能描述:通过url获取资源的绝对路径
     *
     * @param url
     * @return java.lang.String
     * @author zj
     * @date 2021/7/16
     */
    public static String getResourceAbsolutePath(String url) {
        String path = StaticResourceUtil.class.getResource("/").getPath();
//        String[] split = url.split("/");
//        String s = split[split.length - 1];
//        String absolutePath = path.replace("\\\\", "/") + s;
        return url;
    }

    /**
     *
     *功能描述:输出静态资源
     * @param  inputStream 输入流
     * @param  outputStream 输出流
     * @return void
     * @author zj
     * @date 2021/7/16
     */
    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int count = 0;
        while (count == 0){
            count = inputStream.available();
        }
        int resourceSize = count;

        //先输出http响应头，再输出内容
        outputStream.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());

        //已读取内容的长度
        long written = 0;
        //每次读取的长度
        int byteSize = 1024;
        byte[] bytes = new byte[byteSize];

        while (written < resourceSize){
            //判断读取的剩余静态资源长度是否够一个1024长度
            if(written + byteSize > resourceSize){
                //不够 读取剩余长度
                byteSize = (int) (resourceSize-written);
                bytes =  new byte[byteSize];
            }
            inputStream.read(bytes);
            outputStream.write(bytes);
            outputStream.flush();
            written += byteSize;
        }

    }
}
